const express = require('express');
const xml2js = require('xml2js');
const router = express.Router();
const sited = require('../database/db').sited;
const util = require('util');
const decodeXml = require('../core/dbSource').decodeXml;
const getTagContent = require('../core/dbSource').getTagContent;
const DOMParser = require('xmldom').DOMParser;
const os = require('os');


/* GET home page. */
router.get('/', function(req, res, next) {
  res.json({"success":"true"});
});

router.get('/siteds', function(req, res, next) {
    sited.find({},{'xml':false},{sort: {updateTime: -1}},function (error, result) {
        let host;
        if (os.platform() === 'darwin' || os.platform() === 'win32') {
            host = 'http://192.168.0.100:3000'
        } else {
            host = 'http://118.24.83.228'
        }
        const ret = [];
        result.forEach(function (ele, i) {
            let item = {};
            let url = host + '/ddcat/api/ddcat.sited.xml?id='+ele._id;
            item['url'] = 'sited://data?' + (new Buffer(url).toString('base64'));
            item['author'] = ele.author;
            item['title'] = ele.title;
            ret.push(item);
        });
        res.json(ret);
    });
});

router.post('/upload', function(req, res, next) {
    if(!req.files) {
        res.json({success: false, errMsg: '无上传文件'});
        return;
    }
    let msg = '';
    if (!req.files.file) {
        res.json({success:false});
        return;
    }
    let xml = req.files.file.data.toString();
    if (xml.startsWith('<?xml')) {
        msg ='this is normal xml file';
        console.log(msg);

    }else if(xml.startsWith('sited::')) {
        msg ='this is sited encode xml file';
        console.log(msg);
        xml = decodeXml(xml);
    } else {
        msg ='this is not a sited file';
        console.log(msg);
        xml = null;
        res.json({success:false, msg:msg});
        return;
    }

    if(xml) {
        // console.log(xml);
        const doc = new DOMParser().parseFromString(xml);
        let title = getTagContent(doc, 'title');
        let guid = getTagContent(doc, 'guid');
        let intro = getTagContent(doc, 'intro');
        let author = getTagContent(doc, 'author');

        let sited_obj = new sited({
            title: title,
            guid: guid,
            intro: intro,
            author: author,
            xml: xml
        });
        sited_obj.save(function(err) {
            if (err) {
                console.log('保存失败');
                console.log(err);
                msg= '保存失败';
                res.json({success:false, msg:msg});
                return;
            }
            console.log('保存成功');
            msg= '保存成功';
            res.json({success:true, msg:msg});
        });
    }
});


router.get('/system/loginUser', function(req, res, next) {
    res.json({success:true, data:{name:'John'}});
});

router.post('/modify', function (req, res, next) {
    if (req.body.id && req.body.xml) {
        sited.update({_id:req.body.id}, {'$set': {xml:req.body.xml,updateTime:new Date()}}, function (err) {
            if(err) {
                res.send('修改不成功-保存失败');
            }
            res.send('修改成功');
        });

    } else {
        res.send('修改不成功-参数输入不对');
    }
});

router.get('/ddcat.sited.xml', function(req, res, next) {
    if(req.query.id) {
        let id = req.query.id;
        sited.findOne({_id: id},function (error, result) {
            if(error) {
                console.log('error happen');
                res.json({success:false, errMsg:'fail to find'});
                return;
            }
            res.writeHead(200, {
                "Content-Type": 'application/xml'
            });
            res.write(result.xml);
            res.end();
        });
    }else {

    }

});

module.exports = router;
